import { Request, toast, fileUrl } from '../../utils/util.js'
let request = new Request()
let app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    query: {},
    chatList : {},
    isSelf: false,
    userInfo : {}
  },

  load(e) {
    let rows = e.detail.list
    let page = e.detail.page

    if (rows.length == 0 && page == 1) {
      this.setData({ chatList: null })
      return
    }
    if (rows.length > 0) {
      let chatList = this.data.chatList
      rows.forEach(v => {
        switch (v.chat_type) {
          case 1: v.url = '/pages/chat/index'; break;
          case 2:
          case 4:
          case 5: v.url = '/pages/goods/index'; break;
        }
        v.url += '?chatId=' + v.chat_id

        let date = new Date(v.create_time * 1000)
        let m = date.getMonth() + 1
        let d = date.getDate()
        if(m < 10) {
          m = '0' + m
        }
        if (d < 10) {
          d = '0' + d
        }
        let k = m + '' + d

        if (k in chatList) {
          chatList[k].list.push(v)
        }else{
          chatList[k] = {list : [v], m : m, d : d}
        }
      })

      this.setData({ chatList: chatList })
    }
  },


  deleteChat(e) {
    let index = e.currentTarget.dataset.index
    let i = e.currentTarget.dataset.i
    let chatList = this.data.chatList
    let chatId = chatList[index].list[i].chat_id
    wx.showModal({
      title: '删除产品',
      content: '确定删除这个记录吗',

      success: (res) => {
        if (res.confirm) {
          request.delete('chat/delete', res => {
            if (res.success) {
              chatList[index].list.splice(i, 1)
              if (chatList[index].list.length == 0) {
                delete chatList[index]
              }
              console.log(chatList)
              this.setData({ chatList: chatList })
              if ((Object.keys(chatList)).length == 0) {
                this.selectComponent('#pagination').initLoad()
              }
            }else{
              toast(res.msg)
            }
          }, { chatId: chatId })
        }
      }
    })
  },

  onLoad: function (options) {
    let userInfo = app.globalData.userInfo
    let userId = options.userId || 0
    if (userId > 0 && userInfo.user_id != userId) {
      this.setData({ 'query.userId': userId })
      request.get('user/user/' + userId, res => {
        if (res.success) {
          let user = res.data.user
          if (!(user instanceof Object)) {
            user = JSON.parse(user)
          }

          if (user.background) {
            user.background = fileUrl(user.background)
          }

          this.setData({ userInfo: user })
        }
      })

    }else{
      let userInfo = JSON.parse(JSON.stringify(Object.assign(app.globalData.userInfo)))
      if (userInfo.background) {
        userInfo.background = fileUrl(userInfo.background)
      }
      this.setData({ isSelf: true, userInfo: userInfo})
    }
  },

  onShareAppMessage: function () {

  }
})